<template>
  <section class="padding EndWaybillList">
    <el-card>
      <div slot="header" class="clearfix relative ">
        <span class="title-icon">提货地址</span>
        <div class="absolute add-btn-box">
          <el-button
            type="success"
            size="mini"
            icon="el-icon-plus"
            @click="addInfo"
          >
            新增
          </el-button>
        </div>
      </div>

      <el-row>
        <el-col
          v-for="(item, index) in pickupInfo"
          :key="index"
          :md="24"
          :lg="12"
        >
          <div
            class="my-profile-info-box flex justify-between"
            :class="{ 'border-green': item.defaultValue == 1 }"
          >
            <div>
              <div class="margin-bottom">
                <span class="margin-right">联系人：{{ item.linkMan }}</span>
                <span>电话：{{ item.contactWay }}</span>
              </div>
              <div class="margin-bottom">
                {{ item.state + item.city + item.area + item.street }}
              </div>
              <div>{{ item.address }}</div>
            </div>
            <div class="flex justify-between flex-direction">
              <div
                class="pointer"
                :class="item.defaultValue == 1 ? 'text-green' : 'text-red'"
                @click="changeDefault(index)"
              >
                {{ item.defaultValue == 1 ? '默认地址' : '设为默认' }}
              </div>
              <div class="text-lg">
                <el-tooltip content="编辑" effect="light" placement="top-end">
                  <i
                    class="el-icon-edit-outline pointer margin-right"
                    @click="editInfo(index)"
                  />
                </el-tooltip>
                <el-tooltip content="删除" effect="light" placement="top-end">
                  <i class="el-icon-delete pointer" @click="delInfo(index)" />
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- pop -->
    <el-dialog
      title="新增提货地址"
      width="30%"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleForm"
        :rules="rules"
        label-position="left"
        label-width="100px"
        size="mini"
        :model="form"
        class="padding-lr-40"
      >
        <el-form-item prop="linkMan">
          <div slot="label">联系人:</div>
          <el-input
            v-model="form.linkMan"
            placeholder="请填写联系人"
            clearable
          />
        </el-form-item>
        <el-form-item prop="contactWay">
          <div slot="label">联系方式:</div>
          <el-input
            v-model.number="form.contactWay"
            placeholder="请填写联系方式"
            clearable
          />
        </el-form-item>

        <el-form-item prop="provinces">
          <div slot="label">联系地址:</div>
          <el-cascader
            v-model="form.provinces"
            filterable
            :options="cityOptions"
            @change="cityHandleChange"
          />
        </el-form-item>
        <el-form-item prop="address">
          <div slot="label">详细地址:</div>
          <el-input
            v-model="form.address"
            clearable
            placeholder="请填写详细地址"
          />
        </el-form-item>

        <el-form-item prop="defaultValue">
          <div slot="label">是否默认:</div>
          <el-radio-group v-model="form.defaultValue">
            <el-radio :label="parseInt(1)">是</el-radio>
            <el-radio :label="parseInt(0)">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')">{{
          editType == 'add' ? '立即创建' : '保存'
        }}</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { getToken } from '@/utils/auth'
import { clone } from '@/utils/clone'
import { getPcas } from '@/utils/city-pcas.js'
import {
  customerpickupadderssList,
  customerpickupadderssSave,
  customerpickupadderssDelete
} from '@/api/myProfile'
export default {
  name: 'PickUpAddress',
  data() {
    return {
      editType: 'add',
      dialogFormVisible: false,
      form: {
        id: '',
        linkMan: '',
        contactWay: '',
        defaultValue: '',
        street: '',
        address: '',
        state: '',
        city: '',
        area: '',
        provinces: []
      },
      streetList: [],
      cityValue: [],
      cityOptions: getPcas(),
      currentPage: 1,
      searchCriteria: {
        linkMan: '',
        contactWay: ''
      },

      pickupInfo: [],
      rules: {
        linkMan: [{ required: true, message: '请填写联系人', trigger: 'blur' }],
        contactWay: [
          { required: true, message: '请填写联系方式', trigger: 'blur' },
          { type: 'number', message: '请填写正确的联系方式' }
        ],
        address: [
          { required: true, message: '请填写详细地址', trigger: 'blur' }
        ],
        defaultValue: [
          { required: true, message: '请选择是否默认', trigger: 'change' }
        ],
        provinces: [
          { required: true, message: '请选择联系地址', trigger: 'change' }
        ],
        street: [{ required: true, message: '请选择街道', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.init()
    for (let i of this.cityOptions) {
      for (let v of i.children) {
        for (let k of v.children) {
          k.children.push({
            label: '暂不选择',
            value: ''
          })
        }
      }
    }
  },
  methods: {
    async init() {
      this.$store.dispatch('app/toggleDialog', true)
      const data = await customerpickupadderssList({
        authorization: getToken()
      })
      this.pickupInfo = data
      this.$store.dispatch('app/toggleDialog', false)
    },
    addInfo() {
      if (this.pickupInfo.length >= 500) {
        this.dialogFormVisible = false
        this.$message.error('提货地址上限500个')
      } else {
        this.editType = 'add'
        this.dialogFormVisible = true
      }
    },
    editInfo(index) {
      this.editType = 'edit'
      this.dialogFormVisible = true
      // 表达回显重置前提条件
      this.$nextTick(function() {
        this.form = clone(this.pickupInfo[index])
        this.form.contactWay = parseInt(this.form.contactWay)
        this.form.provinces = [
          this.form.state,
          this.form.city,
          this.form.area,
          this.form.street
        ]
      })
    },
    async saveInfo() {
      this.$store.dispatch('app/toggleDialog', true)

      const data = await customerpickupadderssSave(this.form)
      if (data.code === 200) {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.init()
        this.dialogFormVisible = false

        setTimeout(() => {
          this.$refs['ruleForm'].resetFields()
          this.form = {
            id: '',
            linkMan: '',
            contactWay: '',
            defaultValue: '',
            street: '',
            address: '',
            state: '',
            city: '',
            area: '',
            provinces: []
          }
        }, 1000)
      } else {
        this.$message.error(data.message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    delInfo(index) {
      this.$confirm('确认删除？')
        .then(_ => {
          this.$store.dispatch('app/toggleDialog', true)
          customerpickupadderssDelete(this.pickupInfo[index].id).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '已删除',
                type: 'success'
              })
              this.init()
            } else {
              this.$message.error(res.message)
              this.$store.dispatch('app/toggleDialog', false)
            }
          })
        })
        .catch(_ => {})
    },

    cityHandleChange(val) {
      if (!val) return
      this.form.state = val[0]
      this.form.city = val[1]
      this.form.area = val[2]
      this.form.street = val[3]
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveInfo()
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      if (this.$refs[formName]) this.$refs[formName].resetFields()
      this.form = {
        id: '',
        linkMan: '',
        contactWay: '',
        defaultValue: '',
        street: '',
        address: '',
        state: '',
        city: '',
        area: '',
        provinces: []
      }
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.resetForm('ruleForm')
        })
        .catch(_ => {})
    },
    changeDefault(index) {
      this.$confirm('是否将此地址设为默认地址?', '确认操作', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
        .then(() => {
          this.form = this.pickupInfo[index]
          this.form.defaultValue = 1
          this.saveInfo()
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped>
.EndWaybillList >>> .el-textarea__inner {
  min-height: 60px !important;
}
</style>

<style lang="scss" scoped>
.item {
  position: absolute;
  right: -25px;
  top: 3px;
  font-size: 20px;
}

.add-btn-box {
  right: 0;
  top: -6px;
}
</style>
